package info.maxhis.util;

import info.maxhis.bn.R;
import info.maxhis.entity.Friend;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class NetTool {
	public static void main(String[] args) {
		try {
			// 得到图片地址
			byte[] data = readImage("http://imgsrc.baidu.com/forum/pic/item/b2738bd49f8fd32da18bb7a4.jpg");
			FileOutputStream outStream = new FileOutputStream(new File(
					"Img271728976.jpg"));
			outStream.write(data);
			// 关闭流的这个地方需要完善一下
			outStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 声明称为静态变量有助于调用
	public static byte[] readImage(String path) throws Exception {
		URL url = new URL(path);
		// 记住使用的是HttpURLConnection类
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		// 如果运行超过5秒会自动失效 这是android规定
		conn.setConnectTimeout(5 * 1000);
		InputStream inStream = conn.getInputStream();
		// 调用readStream方法
		return readStream(inStream);
	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		// 把数据读取存放到内存中去
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

	/**
	 * 从url中得到图片
	 * @param c
	 * @param url
	 * @return
	 */
	public static synchronized Bitmap getBitMap(Context c, String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			bitmap = BitmapFactory.decodeResource(c.getResources(),
					R.drawable.profile_default);
			return bitmap;
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			int length = (int) conn.getContentLength();
			if (length != -1) {
				byte[] imgData = new byte[length];
				byte[] temp = new byte[512];
				int readLen = 0;
				int destPos = 0;
				while ((readLen = is.read(temp)) > 0) {
					System.arraycopy(temp, 0, imgData, destPos, readLen);
					destPos += readLen;
				}
				bitmap = BitmapFactory.decodeByteArray(imgData, 0,
						imgData.length);
			}
		} catch (IOException e) {
			bitmap = BitmapFactory.decodeResource(c.getResources(),
					R.drawable.profile_default);
			return bitmap;
		}
		return bitmap;
	}
	
}